const Router = require('koa-router')
const rp = require('request-promise-native')
const request = require('request')

const router = new Router()

async function getAccessToken () {
	const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx46c516acaea47659&secret=635f849f0771ce82f81a0264b5cd6292`

	const res = await rp(url)

	return res
}

async function sendUniformMessage (token, id) {

	const url = `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${token}`

	const options = {
		method: 'POST',
		url,
		json: true,
		body: {
			"touser": 'ojoU342DuDQBYL5BD5jxk42CBkI8',
			"template_id": 'OhGghprA8o7XCCusLqiP9uds-glohl7RV74igTX2EIQ',
			"form_id": id,
			"data": {
				"keyword1": {
		        "value": "留"
		      },
		      "keyword2": {
		        "value": "15200000000"
		      },
		      "keyword3": {
		        "value": "睡觉"
		      },
		      "keyword4": {
		        "value": "21044444"
		      },
		      "keyword5": {
		        "value": "21044444"
		      }
			},
			"emphasis_keyword": 'keyword1.DATA'
		}
	}

	const res = await rp(options)

	return res
}

router.get('/wx/:id', async (ctx, next) => {
	const id = ctx.params.id

	let tokenRes = await getAccessToken()

    let token = JSON.parse(tokenRes)

	console.log(token['access_token'])

	let res = await sendUniformMessage(token['access_token'], id)

	console.log(res)

	ctx.body = {
		res
	}
})

router.get('/getopenid', async (ctx, next) => {

  const url = `https://api.weixin.qq.com/sns/jscode2session?&appid=wx46c516acaea47659&secret=635f849f0771ce82f81a0264b5cd6292&js_code=${ctx.query.code}&grant_type=authorization_code`

  const res = await rp(url)

  ctx.body = {
	res
  }
})

module.exports = router
